//
//  EpointNavForPadViewController.m
//  EpointFrame5
//
//  Created by wangzhigang on 14-2-8.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointNavForPadViewController.h"
#import "EpointPadNavCell.h"
#import "EpointMainLoadTask.h"
#import "EpointMainConfigModel.h"
#import "EpointBrowerViewController.h"
#import "EpointLoadMainConfigTask.h"
#import "DBFrameService.h"
#import "EpointNavigationViewController.h"
#import "EpointSettingViewController.h"


@interface EpointNavForPadViewController (){
    BOOL isShowView;
}

@end

@implementation EpointNavForPadViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        viewControllerCacahe = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    [self.view setBackgroundColor:[UIColor blackColor]];
    [self initHJManage];
    dataArr = [EpointLoadMainConfigTask getPhoneArrByStore];
    
//    tv=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, PAD_LEFT_NAV_WIDTH, self.view.frame.size.width)];
    headerIv.hidden=YES;
    headerImg = [[HJManagedImageV alloc] initWithFrame:headerIv.frame];
    headerImg.layer.masksToBounds = YES;
    headerImg.layer.cornerRadius = headerImg.frame.size.height/2;
    headerImg.layer.borderWidth = 2;
    [headerImg.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    headerImg.image = [UIImage imageNamed:@"img_woman"];
    headerImg.url = [NSURL URLWithString:[EpointBizTools getUserHeadImageDataUrl:[DBFrameService getUserGuid]]];
    [headerView addSubview:headerImg];
    [objMan manage:headerImg];
    NSString *name = (NSString *)[DBFrameService getUserDefaults:Epoint_User_DisplayName];
    displayNameLb.text = name;
    headerIvLayout.backgroundColor=COLOR(91, 67, 106);
    tv.backgroundColor = COLOR(91, 67, 106);
    tv.width=PAD_LEFT_NAV_WIDTH_CONST;
    headerIvLayout.width=PAD_LEFT_NAV_WIDTH_CONST;
    versionLb.width =PAD_LEFT_NAV_WIDTH_CONST;
    tv.delegate=self;
    tv.dataSource=self;
    tv.separatorColor=[UIColor clearColor];
    versionLb.backgroundColor = COLOR(58, 41, 60);
    isShowView = NO;
    if (dataArr.count>0) {
        [self performSelector:@selector(showView) withObject:self afterDelay:0.5];
    }
    
    
    
    NSString *clientDisplayName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    NSString *clientVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    versionLb.text =[NSString stringWithFormat:@"%@V%@",clientDisplayName,clientVersion];
    
    
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.view.height=AppHeight;
    self.view.width=AppWidth+PAD_LEFT_NAV_WIDTH;

    if ([UIDevice currentDevice].systemVersion.floatValue < 7.0) {
        versionLb.top=versionLb.top-StatusBarHeight;
        tv.height=tv.height-StatusBarHeight;
    }
}

-(void)showView{
        isShowView=YES;
        EpointMainConfigModel *m = [dataArr objectAtIndex:XAppDelegate.clickPos];
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        NSData* aData = [m.paData dataUsingEncoding: NSUTF8StringEncoding];
        NSError *error;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
        for (NSString *key in [json keyEnumerator]) {
            [params setObject:[json objectForKey:key] forKey:key];
        }
        [params setObject:m.modulename forKey:@"title"];
        EpointPhoneViewController *c = [[NSClassFromString(m.launchclass) alloc]init];
        c.passParam = params;
        EpointNavigationViewController *uv = [[EpointNavigationViewController alloc]initWithRootViewController:c:YES];
        [XAppDelegate.stackController pushViewController:uv animated:NO];
    
}

//初始化图片缓存管理器
-(void)initHJManage
{
    objMan = [[HJObjManager alloc] initWithLoadingBufferSize:20 memCacheSize:30];
    NSString* cacheDirectory = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/imgcache/flickr/"] ;
    HJMOFileCache* fileCache = [[HJMOFileCache alloc] initWithRootPath:cacheDirectory];
    objMan.fileCache = fileCache;
    fileCache.fileCountLimit = 100;
    fileCache.fileAgeLimit = 60*60*24*30; //1 week
    [fileCache trimCacheUsingBackgroundThread];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self startTask:@"EpointLoadMainConfigTask" withParams:nil withTaskId:1];
}

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    if (taskId==1) {
        dataArr = (NSMutableArray *)obj;
        [tv reloadData];
        [self startTask:@"User_GetInfo_Task" withParams:nil withTaskId:2];
    }else if (taskId==2)
    {
        NSMutableArray *arr = (NSMutableArray*)obj;
        NSMutableArray *listData = [arr objectAtIndex:2];
        for (int i=0;i<dataArr.count;i++) {
            EpointMainConfigModel *m = [dataArr objectAtIndex:i];
            if ([m.moduleID isEqualToString:@"2"]) {
                m.tips = [listData objectAtIndex:1];
                [dataArr replaceObjectAtIndex:i withObject:m];
            }
            else if ([m.moduleID isEqualToString:@"3"])
            {
                m.tips = [listData objectAtIndex:0];
                [dataArr replaceObjectAtIndex:i withObject:m];
            }
        }
        [tv reloadData];
        if (!isShowView) {
            [self performSelector:@selector(showView) withObject:self afterDelay:0.5];
        }
    }

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"EpointPadNavCell";
    EpointPadNavCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell==nil) {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"EpointPadNavCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    cell.backgroundColor = [UIColor clearColor];
    EpointMainConfigModel *m = [dataArr objectAtIndex:indexPath.row];
    cell.navItemName.text=m.modulename;
    [cell.navItemIcon setImage:[UIImage imageNamed:@"img_icobg"]];
    cell.navItemIcon.url=[NSURL URLWithString:[EpointBizTools getUrl:[NSString stringWithFormat:@"mobileconfig/mainimg/%@",m.iconUrl]]];
    cell.navItemIcon.isloadTinColor = YES;
    cell.navItemIcon.itintColor = [UIColor whiteColor];
    [objMan manage:cell.navItemIcon];
    
    cell.navItemTips.layer.cornerRadius = 9;
    cell.navItemTips.backgroundColor = [UIColor lightGrayColor];
    cell.navItemTips.text=m.tips;
    cell.navItemTips.textColor=[UIColor whiteColor];
    if ([m.tips intValue]>0) {
        cell.navItemTips.hidden=NO;
    }else{
        cell.navItemTips.hidden=YES;
    }
    return cell;
}


#pragma mark - Table view delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     PSStackedViewController *stackController = XAppDelegate.stackController;
    while ([stackController.viewControllers count]) {
        [stackController popViewControllerAnimated:YES];
    }
    if (indexPath.row==0) {
        [XAppDelegate.stackController dismissViewControllerAnimated:YES completion:nil];
        return;
    }

    // Navigation logic may go here. Create and push another view controller.
    
    EpointMainConfigModel *m = [dataArr objectAtIndex:indexPath.row];
    if ([m.type isEqualToString:@"2"]) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:m.dyUrl forKey:@"url"];
        [params setObject:m.modulename forKey:@"title"];
        EpointBrowerViewController *vc = [[EpointBrowerViewController alloc]init];
        vc.passParam = params;
        EpointNavigationViewController *uv = [[EpointNavigationViewController alloc]initWithRootViewController:vc:YES];
        [XAppDelegate.stackController pushViewController:uv fromViewController:nil animated:NO];

    }
    else if([m.type isEqualToString:@"1"])
    {
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        NSData* aData = [m.paData dataUsingEncoding: NSUTF8StringEncoding];
        NSError *error;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
        for (NSString *key in [json keyEnumerator]) {
            [params setObject:[json objectForKey:key] forKey:key];
        }
        [params setObject:m.modulename forKey:@"title"];
        EpointPhoneViewController *c = [[NSClassFromString(m.launchclass) alloc]init];
        c.passParam = params;
        EpointNavigationViewController *uv = [[EpointNavigationViewController alloc]initWithRootViewController:c:YES];
        [XAppDelegate.stackController pushViewController:uv fromViewController:nil animated:NO];
    }
    else if ([m.type isEqualToString:@"3"])
    {
        if (![[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:m.launchclass]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:m.apkUrl]];
        }
        else
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:m.launchclass]];
        }
    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
